﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using CRM.Business.Services;
using CRM.DataAccess.Entities;
using CRM.Encryption;
using System.Web.Security;
using System.Net;
using System.Net.Mail;

namespace Web.Account
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
                return;
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                USER user = UserService.UserLogin(txtUsername.Text, RSAEncryption.PrivateEncryption(txtPassword.Text));
                if (user != null)
                {
                    ROLE r = RoleService.GetRoleByID((long)user.ROLE_ID);
                    if ((bool)r.ACTIVE)
                    {
                        if ((bool)user.ACTIVE)
                        {
                            Session["User"] = user;
                            FormsAuthentication.RedirectFromLoginPage(user.USER_NAME, true);
                        }
                        else
                            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert('Your account is not Active! Please contact Administrator !');", true);
                    }
                    else
                        ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert('Your Role is not Active ! Please contact Administrator !');", true);

                }

                else
                    ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert('Username or Password is incorrect !');", true);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert('Can not login !');", true);
            }
        }
        private readonly Random _rng = new Random();
        private const string _chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

        private string RandomString(int size)
        {
            char[] buffer = new char[size];

            for (int i = 0; i < size; i++)
            {
                buffer[i] = _chars[_rng.Next(_chars.Length)];
            }
            return new string(buffer);
        }
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            int checkUserexist = UserService.CheckExist(txtForgotUserName.Text.Trim());

            if (checkUserexist == 1)
            {
               
                USER user = UserService.GetUserByUsername(txtForgotUserName.Text.Trim());
                string newpass = RandomString(8);
                user.USER_HASH = RSAEncryption.PrivateEncryption(newpass);
                int updatenewpass = UserService.UpdateUser(user);
                string subject = "Your Xtab Account : Forgot password!";
                string adminEmail = "xtab.message@gmail.com";
                string message;
                if (updatenewpass == 1)
                {
                    message = "Dear " + user.USER_NAME + ",\r\n\r\n" +
                        "Your new password :" + newpass;
                    string res = SendMail(txtEmail.Text.Trim(), adminEmail, "", subject, message);
                    ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "","alert('Message: "+ res +"');" , true);
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert('Can not reset password ! Please contact Administrator !');", true);
                }
            }
            else
            {
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert('User is not exist !');", true);
            }

        }
        public string SendMail(string toList, string from, string ccList, string subject, string body)
        {
            MailMessage message = new MailMessage();
            SmtpClient smtpClient = new SmtpClient();
            string msg = string.Empty;
            try
            {
                MailAddress fromAddress = new MailAddress(from);
                message.From = fromAddress;
                message.To.Add(toList);
                if (ccList != null && ccList != string.Empty)
                    message.CC.Add(ccList);
                message.Subject = subject;
                message.IsBodyHtml = false;
                message.Body = body;
                smtpClient.Host = "smtp.gmail.com";   // We use gmail as our smtp client
                smtpClient.Port = 587;
                smtpClient.EnableSsl = true;
                smtpClient.UseDefaultCredentials = true;
                smtpClient.Credentials = new System.Net.NetworkCredential("xtab.message@gmail.com", "xtablish888");

                smtpClient.Send(message);
                msg = "Successful ! Please check your email !";
            }
            catch (Exception ex)
            {
                msg = " Error! Please try again or contact to Adminstrator !";
            }
            return msg;
        }
    }
}